<!--
 * @Author: 又帅又爱学习 501879094@qq.com
 * @Date: 2022-09-21 16:16:15
 * @LastEditors: 又帅又爱学习 501879094@qq.com
 * @LastEditTime: 2022-10-17 17:41:50
 * @FilePath: /vue_demo/src/views/Demo06.vue
 * @Description: 这是默认设置
-->
<template>
  <div class="root">
    <transition-group
      tag="div"
      class="container"
    >
      <div
        v-for="(item, i) in items"
        :key="item.key"
        class="item"
        :class="'item' + i"
        :style="{ 'background-color': item.color, border: '1px solid' }"
        :draggable="item.draggable"
        @dragstart="handleDragStart($event, item)"
        @dragover.prevent="handleDragOver($event, item)"
        @dragenter="handleDragEnter($event, item)"
        @dragend="handleDragEnd($event, item)"
      >
        <div>{{ item }}</div>
      </div>
    </transition-group>
  </div>
</template>

<script>
export default {
  name: 'Toolbar',
  data() {
    return {
      items: [
        { key: 1, color: '#3883a0', draggable: true },
        { key: 2, color: '#4883a0', draggable: false },
        { key: 3, color: '#5883a0', draggable: true },
        { key: 4, color: '#6883a0', draggable: true },
        { key: 5, color: '#7883a0', draggable: true },
        { key: 6, color: '#8883a0', draggable: true },
        { key: 7, color: '#9883a0', draggable: true }
      ],
      ending: null,
      dragging: null
    }
  },
  created() {
    let x = 1
    let y = 2
    ;[x, y] = [y, x]
    console.warn(x, y)
  },
  methods: {
    // eslint-disable-next-line no-unused-vars
    handleDragStart(e, item) {
      this.dragging = item
    },
    // eslint-disable-next-line no-unused-vars
    handleDragEnd(e, item) {
      if (this.ending.key === this.dragging.key) {
        return
      }
      const newItems = [...this.items]
      const src = newItems.indexOf(this.dragging)
      const dst = newItems.indexOf(this.ending)
      newItems.splice(src, 1, ...newItems.splice(dst, 1, newItems[src]))
      console.log(newItems)
      this.items = newItems
      this.$nextTick(() => {
        this.dragging = null
        this.ending = null
      })
    },
    handleDragOver(e) {
      // 首先把div变成可以放置的元素，即重写dragenter/dragover
      // 在dragenter中针对放置目标来设置
      e.dataTransfer.dropEffect = 'move'
    },
    handleDragEnter(e, item) {
      // 为需要移动的元素设置dragstart事件
      e.dataTransfer.effectAllowed = 'move'
      this.ending = item
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-wrap: wrap;
}
.item {
  width: 200px;
  height: 200px;
  margin: 10px;
  color: #fff;
  transition: all linear 0.3s;
}
.item0 {
  width: 400px;
}
</style>
